// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2023 Yevhen Babiichuk (DustDFG)

#include <Abracadabra/View/Tube.hpp>

namespace View
{

Tube::Tube(uint8_t size, sf::FloatRect boundsRect, Theme* theme)
	: ISFMLTube(size, boundsRect)
	, slots(size, sf::RectangleShape())
	, theme(theme)
{
	float width = boundsRect.width;
	float height = boundsRect.height / this->size;

	for(uint8_t i = 0; i < this->size; ++i)
	{
		slots[i].setSize({width, height});
		slots[i].setPosition({boundsRect.left, boundsRect.top + (height * i)});
	}
}

void Tube::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
	for(uint8_t i = 0; i < this->size; ++i)
	{
		target.draw(this->slots[i]);
	}
}

void Tube::fillSlot(uint8_t slotIndex, sf::Texture* texture, sf::IntRect textureRect)
{
	this->slots[this->size - 1 - slotIndex].setTexture(texture);
	this->slots[this->size - 1 - slotIndex].setTextureRect(textureRect);
}

void Tube::fillSlotDot(uint8_t slotIndex, std::optional<uint8_t> dot)
{
	sf::IntRect textureRect;
	if(dot)
	{
		textureRect = {this->theme->dotTextureW * dot.value(), 0, this->theme->dotTextureW, this->theme->dotTextureH};
	}
	else
	{
		textureRect = {0, 0, 0, 0};
	}
	this->fillSlot(slotIndex, &this->theme->dotsTexture, textureRect);
}

void Tube::fillSlotTubePart(uint8_t slotIndex, uint8_t partIndex)
{
	sf::IntRect textureRect = {0, this->theme->tubePartTextureH * partIndex, this->theme->tubePartTextureW, this->theme->tubePartTextureH};
	this->fillSlot(slotIndex, &this->theme->tubeTexture, textureRect);
}

void Tube::fillSlotSelectedTubePart(uint8_t slotIndex, uint8_t partIndex)
{
	sf::IntRect textureRect = {0, this->theme->tubePartTextureH * partIndex, this->theme->tubePartTextureW, this->theme->tubePartTextureH};
	this->fillSlot(slotIndex, &this->theme->selectedTubeTexture, textureRect);
}
}
